package netty.c1.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author ChenweiLin
 * @create 2022-02-09 9:22
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        socketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = channelFuture.sync().channel();
        log.debug("{}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if ("q".equals(line)){
                    channel.close();//close 是一个异步操作 关闭需要大约1s
//                    log.debug("处理关闭之后的操作");//不能在这里善后
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"input").start();

        //执行真正的关闭操作
        //获取closedFuture对象， 1) 同步处理关闭，2)异步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        //同步处理关闭 发生在主线程中
        System.out.println("waiting close...");
        closeFuture.sync();
        log.debug("处理关闭之后的操作");//[main] DEBUG netty.c1.c3.CloseFutureClient - 处理关闭之后的操作 （发生在主线程中）

        closeFuture.addListener((ChannelFutureListener) future -> {
            log.debug("处理关闭之后的操作");//[nioEventLoopGroup-2-1] DEBUG netty.c1.c3.CloseFutureClient - 处理关闭之后的操作(发生在nio线程中，即做到了异步)
            group.shutdownGracefully();//停止整个时间循环组，整个Java线程结束，如果没执行该操作，由于group里面还有其他线程，整个Java线程不会结束
        });
    }
}
